package com.qf.filters;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
@Order(-5)  //控制过滤器的执行优先级，值越小，优先级越高
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //放行掉一些登录、注册相关资源

        //做一些登录验证
        ServerHttpRequest request = exchange.getRequest();
        //获取请求参数
        String token = request.getQueryParams().getFirst("token");

        //实际这里拿到的是一个jwt串，我们要对这个jwt串进行验证，验证通过放行，验证失败，或者超时，都需要阻止放行，并响应友好提示给页面端

        if (token == null){
            //没有携带token，认为没有登陆，不放行， 要响应一些数据到前端
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //没有登录的验证码 401

            //解决中文乱码
            response.getHeaders().set("content-type","application/json;charset=utf-8");

            //利用webflux的响应对象，向前端页面响应数据
            R r = R.error().putMsg("尚未登录，请先登录");
            String json = JSON.toJSONString(r);
            DataBuffer wrap = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(wrap));
        }

        //放行
        return chain.filter(exchange);
    }
}
